from flask import Blueprint, request
from flask_demo.entities import LogicComponent
from flask_demo import app_database
import os


logic_component_blue_print = Blueprint("logic_component_blue_print", __name__, url_prefix="/logic_component")


@logic_component_blue_print.route("/mine", methods=["get", ])
def get_logic_component_mine():
    res_list = None
    user_id = request.args.get("user_id")
    success = False
    try:
        res_list = LogicComponent.query.filter(LogicComponent.author_id == int(user_id)).all()
        success = True
        pass
    except:
        success = False
        print("Error: get_logic_component_mine. ")
        pass
    return {
        "success": success,
        "data": {
            "dataList": [i.to_dict1() for i in res_list] if res_list is not None else []
        }
    }


@logic_component_blue_print.route("/all", methods=["get", ])
def get_logic_component_all():
    res_list = None
    success = False
    try:
        res_list = LogicComponent.query.all()
        success = True
        pass
    except:
        success = False
        print("Error: get_logic_component_mine. ")
        pass
    return {
        "success": success,
        "data": {
            "dataList": [i.to_dict1() for i in res_list] if res_list is not None else []
        }
    }


@logic_component_blue_print.route("/public", methods=["get", ])
def get_logic_component_public():
    return {
        "ok": True,
        "dataList": []
    }


@logic_component_blue_print.route("/new", methods=["post", ])
def post_logic_component_new():
    logic_component_id = -1
    success = False
    try:
        author_id = request.json.get("author_id")
        title = request.json.get("title")
        img_url = request.json.get("img_url")
        group_name = request.json.get("group_name")
        text_str = request.json.get("text_str")
        type_int = request.json.get("type_int")
        middle_parameter = request.json.get("middle_parameter")
        input_parameter = request.json.get("input_parameter")
        output_parameter = request.json.get("output_parameter")
        file_path = request.json.get("file_path")
        lc = LogicComponent(
            author_id=int(author_id),
            title=title,
            img_url=img_url,
            group_name=group_name,
            text_str=text_str,
            type_int=int(type_int),
            middle_parameter=middle_parameter,
            input_parameter=input_parameter,
            output_parameter=output_parameter,
            public=0,
            file_path=file_path,
        )
        app_database.session.add(lc)
        app_database.session.commit()
        logic_component_id = lc.logic_component_id
        success = True
        pass
    except:
        success = False
        print("Error: post_logic_component_new")
        pass
    return {
        "success": success,
        "data": {
            "logic_component_id": logic_component_id
        }
    }


@logic_component_blue_print.route("/delete", methods=["post", ])
def post_logic_component_delete():
    return {
        "ok": True,
    }


@logic_component_blue_print.route("/publish", methods=["post", ])
def post_logic_component_publish():
    return {
        "ok": True,
    }


@logic_component_blue_print.route("/cancel", methods=["post", ])
def post_logic_component_cancel():
    return {
        "ok": True,
    }


@logic_component_blue_print.route("/file", methods=["post", ])
def post_logic_component_file():
    success = False
    file_path = "None"
    user_id_str = str(request.form['user_id'])
    if user_id_str is None:
        print("Error: user_id_str is None. ")
        pass
    elif 'file' in request.files:
        file = request.files['file']
        if file.filename.endswith(".py"):
            # file_path = os.path.join("/upload_py_file", file.filename)
            # 如果不存在这个文件夹，就进行创建，如果是直接 / 加上路径，就相当于是直接在C盘目录下创建
            # 如果是不加 /，是在 starter01.py 下创建了
            dir_str = "upload_py_file"
            if not os.path.exists(dir_str):
                os.mkdir(dir_str)
                pass
            dir_str = dir_str + "/" + user_id_str
            if not os.path.exists(dir_str):
                os.mkdir(dir_str)
                pass
            file_path = dir_str + "/" + file.filename
            # print("file_path", file_path, os.path)
            file.save(file_path)
        pass
    return {
        "success": success,
        "data": {
            "file_path": file_path
        }
    }
